package com.iqilu.ksd.fragment;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.TVChannelAdapter;
import com.iqilu.ksd.bean.TVBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.RadioInfo;
import com.iqilu.ksd.event.StopPlayRadioEvent;
import com.iqilu.ksd.event.StopPlayVideoEvent;
import com.iqilu.ksd.service.RadioService;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.NetworkUtils;
import com.iqilu.ksd.utils.TVUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import okhttp3.Call;

/**
 * Created by Coofee on 2016/11/15.
 */

public class RadioListFragment extends BaseFragment implements View.OnClickListener{

    private static final String TAG = "RadioListFragment";

    private TVBean tvBean;
    private int curRadioId;

    private ArrayList<TVBean> list;
    private ArrayList<TVBean> radioList;
    private TVChannelAdapter adapter;

    private RelativeLayout layProgress;
    private SimpleDraweeView imgThumb;
    private ImageView btPlay;
    private TextView tvTime;
    private TextView tvDuration;
    private SeekBar skProgress;
    private ListView lvList;
    private RelativeLayout layLoading;

    private Animation roateAni;
    private LocalBroadcastManager localBroadcastManager;
    private boolean isRegisterReceivers = false;
    private RadioService radioService;
    private boolean isBound = false;
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            radioService = ((RadioService.RadioBinder) service).getService();
            isBound = true;
            initUI(radioService.getCurRadioId(), radioService.isRunning());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false;
        }
    };

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(RadioInfo.RECEIVER_MEDIAPLAYER_STATUS)) {
                if (intent.hasExtra(RadioInfo.RECEIVER_MEDIAPLAYER_STATUS)) {
                    String status = intent.getStringExtra(RadioInfo.RECEIVER_MEDIAPLAYER_STATUS);
                    if (status.equals(RadioInfo.STATUS_LAST)) {
                        lastChannel();
                    } else if (status.equals(RadioInfo.STATUS_NEXT)) {
                        nextChannel();
                    } else if (status.equals(RadioInfo.STATUS_STOP)) {
                        btPlay.setImageResource(R.drawable.bt_radio_play);
                        imgThumb.clearAnimation();
                    } else if (status.equals(RadioInfo.STATUS_PLAY)) {
                        btPlay.setImageResource(R.drawable.bt_radio_pause);
                        imgThumb.setAnimation(roateAni);
                        imgThumb.animate();
                    }
                }
            }
        }
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_radiolist, null);
        lvList = getView(view,R.id.lv_list);
        layLoading = getView(view,R.id.lay_loading);
        imgThumb = getView(view, R.id.img_thumb);
        btPlay = getView(view, R.id.bt_play);
        btPlay.setOnClickListener(this);
        layProgress = getView(view, R.id.lay_progress);
        layProgress.setVisibility(View.GONE);
        tvTime = getView(view, R.id.tv_time);
        tvDuration = getView(view, R.id.tv_duration);
        skProgress = getView(view, R.id.sk_progress);
        bindServices();
        registerReceivers();
        tvBean = TVUtils.getNews();
        curRadioId = tvBean.getId();
        imgThumb.setImageURI(Uri.parse("res://"+context.getPackageName()+"/"+tvBean.getImgResorceId()));
        roateAni = AnimationUtils.loadAnimation(context, R.anim.rotate_radio);
        LinearInterpolator lin = new LinearInterpolator();
        roateAni.setInterpolator(lin);

        adapter = new TVChannelAdapter(context,"radio");
        lvList.setAdapter(adapter);
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tvBean = radioList.get(position);
                toPlay();
            }
        });
        radioList = TVUtils.getRadioList();
        getList();
        return view;
    }

    public void bindServices() {
        Intent intent = new Intent(context, RadioService.class);
        context.bindService(intent, mConnection, context.BIND_AUTO_CREATE);
    }

    public void registerReceivers() {
        isRegisterReceivers = true;
        localBroadcastManager = LocalBroadcastManager.getInstance(context);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(RadioInfo.RECEIVER_MEDIAPLAYER_STATUS);
        intentFilter.addAction(RadioInfo.RECEIVER_MEDIAPLAYER_CONTENT);
        localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    private void toPlay(){
        if(NetworkUtils.isAvailable(context) && ! NetworkUtils.isWifiConnected(context)){
            showSelectDialog();
        }else {
            play();
        }
    }

    private void showSelectDialog() {
        final MaterialDialog dialog = new MaterialDialog(context);
        dialog.content(getString(R.string.not_wifi))
                .btnText(getString(R.string.cancel), getString(R.string.continue_play))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        play();
                        dialog.dismiss();
                    }
                }
        );
    }

    private void play() {
        imgThumb.setImageURI(Uri.parse("res://"+context.getPackageName()+"/"+tvBean.getImgResorceId()));
        imgThumb.startAnimation(roateAni);
        btPlay.setImageResource(R.drawable.bt_radio_pause);
        Intent intent = new Intent(context, RadioService.class);
        intent.setAction(RadioInfo.SERVICE_MEDIAPLAYER_PLAY);
        intent.putExtra(RadioInfo.CURRADIOID, tvBean.getId());
        context.startService(intent);
        adapter.setCurId(tvBean.getId());
        adapter.notifyDataSetChanged();
        EventBus.getDefault().post(new StopPlayVideoEvent());
    }

    public void stop() {
        imgThumb.clearAnimation();
        btPlay.setImageResource(R.drawable.bt_radio_play);
        Intent intent = new Intent(context, RadioService.class);
        intent.setAction(RadioInfo.SERVICE_MEDIAPLAYER_STOP);
        context.startService(intent);
    }

    private void nextChannel() {
        curRadioId = radioService.getCurRadioId();
        Log.i(TAG,"nextChannel curRadioId="+curRadioId);
        tvBean = TVUtils.getRadioById(curRadioId);
        imgThumb.setImageURI(Uri.parse("res://"+context.getPackageName()+"/"+tvBean.getImgResorceId()));
        play();
    }

    private void lastChannel() {
        curRadioId = radioService.getCurRadioId();
        tvBean = TVUtils.getRadioById(curRadioId);
        imgThumb.setImageURI(Uri.parse("res://"+context.getPackageName()+"/"+tvBean.getImgResorceId()));
        play();
    }

    private void initUI(int curRadioId, boolean isRunning) {
        this.curRadioId = curRadioId;
        tvBean = TVUtils.getRadioById(curRadioId);
        if (isRunning) {
            imgThumb.setImageURI(Uri.parse("res://"+context.getPackageName()+"/"+tvBean.getImgResorceId()));
            imgThumb.startAnimation(roateAni);
            btPlay.setImageResource(R.drawable.bt_radio_pause);
        } else {
            imgThumb.setImageURI(Uri.parse("res://"+context.getPackageName()+"/"+tvBean.getImgResorceId()));
            imgThumb.clearAnimation();
            btPlay.setImageResource(R.drawable.bt_radio_play);
        }
    }

    private void getList() {
        String url = Api.URL_RADIO_CHANNEL;
        OkHttpUtils.get().url(url).tag(context).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                adapter.setData(radioList);
                adapter.notifyDataSetChanged();
                layLoading.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(String response, int id) {
                ArrayList<TVBean> mList = null;
                list = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<TVBean>>() {
                });
                mList = setPlaying(radioList, list);
                adapter.setData(mList);
                adapter.notifyDataSetChanged();
                layLoading.setVisibility(View.GONE);
            }
        });
    }

    private ArrayList<TVBean> setPlaying(ArrayList<TVBean> local, ArrayList<TVBean> remote) {
        if (remote == null || remote.size() == 0 || remote.size() < local.size()) {
            return local;
        }
        for (int i = 0; i < local.size(); i++) {
            for (int j = 0; j < remote.size(); j++) {
                if (local.get(i).getId() == remote.get(j).getId()) {
                    local.get(i).setPlaying(remote.get(j).getPlaying());
                    local.get(i).setImg(remote.get(j).getImg());
                    break;
                }
            }
        }
        return local;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_play:
                if (radioService.isRunning()) {
                    stop();
                } else {
                    toPlay();
                }
                break;
            default:
                break;
        }
    }
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(ChannelChangeEvent event) {
//        if(event.getType().equals("radio")) {
//            tvBean = TVUtils.getRadioById(event.getId());
//            toPlay();
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(StopPlayRadioEvent event) {
        if (radioService.isRunning()) {
            stop();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

}
